package com.hwpt.hwaccount.feature.feedback;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hwpt.hwaccount.R;
import com.hwpt.hwaccount.core.data.local.dao.UserDao;
import com.hwpt.hwaccount.core.data.remote.api.ApiService;

import java.util.ArrayList;
import java.util.List;

public class FeedbackActivity extends AppCompatActivity implements FeedbackContract.View {
    
    private static final int PICK_IMAGE_REQUEST = 1;
    
    private TextView feedbackTypeText;
    private EditText descriptionEdit;
    private TextView charCountText;
    private EditText phoneEdit;
    private Button submitButton;
    private LinearLayout imagePreviewContainer;
    private List<Uri> selectedImages = new ArrayList<>();
    
    private FeedbackContract.Presenter presenter;
    private ApiService apiService;
    private UserDao userDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback);
        
        // 初始化Presenter和Model
        FeedbackContract.Model model = new FeedbackModel(this, apiService, userDao);
        presenter = new FeedbackPresenter(model);
        presenter.attachView(this);
        
        initViews();
        setupListeners();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.detachView();
    }
    
    private void initViews() {
        feedbackTypeText = findViewById(R.id.feedback_type_text);
        descriptionEdit = findViewById(R.id.description_edit);
        charCountText = findViewById(R.id.char_count_text);
        phoneEdit = findViewById(R.id.phone_edit);
        submitButton = findViewById(R.id.submit_button);
        imagePreviewContainer = findViewById(R.id.image_preview_container);
        
        LinearLayout feedbackTypeContainer = findViewById(R.id.feedback_type_container);
        feedbackTypeContainer.setOnClickListener(v -> presenter.onFeedbackTypeClicked());
        
        ImageButton addImageButton = findViewById(R.id.add_image_button);
        addImageButton.setOnClickListener(v -> selectImage());
    }
    
    private void setupListeners() {
        // 字符计数监听
        descriptionEdit.addTextChangedListener(new TextWatcher() {
            @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                charCountText.setText(s.length() + "/200");
                presenter.onDescriptionChanged(s, start, before, count);
            }
            
            @Override
            public void afterTextChanged(Editable s) {}
        });
        
        // 提交按钮监听
        submitButton.setOnClickListener(v -> presenter.onSubmitClicked());
    }
    
    @Override
    public void showFeedbackTypeDialog() {
        Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.dialog_feedback_types);
        
        RecyclerView recyclerView = dialog.findViewById(R.id.feedback_types_recycler);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        
        List<FeedbackModel.FeedbackType> types = presenter.getFeedbackTypes();
        FeedbackTypeAdapter adapter = new FeedbackTypeAdapter(types, type -> {
            if (!type.getCategory().isEmpty()) { // 不是分类标题
                setFeedbackTypeText(type.getName(), getResources().getColor(android.R.color.black));
                dialog.dismiss();
            }
        });
        
        recyclerView.setAdapter(adapter);
        dialog.show();
    }
    
    private void selectImage() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "选择图片"), PICK_IMAGE_REQUEST);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        presenter.onImageSelected(requestCode, resultCode, data);
    }
    
    @Override
    public void onImageSelectionResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
            if (data != null) {
                if (data.getClipData() != null) {
                    // 多选图片
                    int count = data.getClipData().getItemCount();
                    for (int i = 0; i < count; i++) {
                        Uri imageUri = data.getClipData().getItemAt(i).getUri();
                        selectedImages.add(imageUri);
                    }
                } else if (data.getData() != null) {
                    // 单选图片
                    Uri imageUri = data.getData();
                    selectedImages.add(imageUri);
                }
            }
        }
    }
    
    @Override
    public void updateImagePreview() {
        imagePreviewContainer.removeAllViews();
        
        if (selectedImages.isEmpty()) {
            imagePreviewContainer.setVisibility(View.GONE);
            return;
        }
        
        imagePreviewContainer.setVisibility(View.VISIBLE);
        
        for (Uri imageUri : selectedImages) {
            ImageView imageView = new ImageView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(100, 100);
            params.setMargins(0, 0, 8, 0);
            imageView.setLayoutParams(params);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setImageURI(imageUri);
            
            imagePreviewContainer.addView(imageView);
        }
    }
    
    @Override
    public void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public void clearForm() {
        setFeedbackTypeText("请选择问题类型", getResources().getColor(android.R.color.darker_gray));
        descriptionEdit.setText("");
        phoneEdit.setText("");
        selectedImages.clear();
        updateImagePreview();
    }
    
    @Override
    public void setFeedbackTypeText(String text, int color) {
        feedbackTypeText.setText(text);
        feedbackTypeText.setTextColor(color);
    }
    
    @Override
    public String getFeedbackType() {
        return feedbackTypeText.getText().toString();
    }
    
    @Override
    public String getDescription() {
        return descriptionEdit.getText().toString();
    }
    
    @Override
    public String getPhone() {
        return phoneEdit.getText().toString();
    }
    
    @Override
    public List<Uri> getSelectedImages() {
        return selectedImages;
    }
    
    // FeedbackTypeAdapter类（需要调整使用FeedbackModel.FeedbackType）
    private class FeedbackTypeAdapter extends RecyclerView.Adapter<FeedbackTypeAdapter.ViewHolder> {
        
        private List<FeedbackModel.FeedbackType> types;
        private OnItemClickListener listener;
        
        public FeedbackTypeAdapter(List<FeedbackModel.FeedbackType> types, OnItemClickListener listener) {
            this.types = types;
            this.listener = listener;
        }
        
        @Override
        public ViewHolder onCreateViewHolder(android.view.ViewGroup parent, int viewType) {
            View view = getLayoutInflater().inflate(android.R.layout.simple_list_item_1, parent, false);
            return new ViewHolder(view);
        }
        
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            FeedbackModel.FeedbackType type = types.get(position);
            holder.textView.setText(type.getName());
            
            // 分类标题样式
            if (type.getCategory().isEmpty()) {
                holder.textView.setTextSize(16);
                holder.textView.setTypeface(null, android.graphics.Typeface.BOLD);
                holder.itemView.setEnabled(false);
            } else {
                holder.textView.setTextSize(14);
                holder.textView.setTypeface(null, android.graphics.Typeface.NORMAL);
                holder.itemView.setEnabled(true);
            }
            
            holder.itemView.setOnClickListener(v -> {
                if (listener != null && !type.getCategory().isEmpty()) {
                    listener.onItemClick(type);
                }
            });
        }
        
        @Override
        public int getItemCount() {
            return types.size();
        }
        
        class ViewHolder extends RecyclerView.ViewHolder {
            TextView textView;
            
            ViewHolder(View itemView) {
                super(itemView);
                textView = itemView.findViewById(android.R.id.text1);
            }
        }
        
        interface OnItemClickListener {
            void onItemClick(FeedbackModel.FeedbackType type);
        }
    }
}